package vn.vfriends.id.bean;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named("languageBean")
@SessionScoped
public class LanguageBean implements Serializable {

    Logger logger = LoggerFactory.getLogger(LanguageBean.class);
    private String language = "";
    private Locale currentLocale;
    private Map<String, String> map = new HashMap<String, String>();

    public LanguageBean() {
        currentLocale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
        map.put("en", "US");
        map.put("vi", "VN");
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public Locale getCurrentLocale() {
        return currentLocale;
    }

    public String changeLanguageAction() {
        try {
            if (this.language == null) {
                return null;
            }
            this.currentLocale = new Locale(this.language, map.get(this.language));
            FacesContext.getCurrentInstance().getViewRoot().setLocale(this.currentLocale);
            FacesContext.getCurrentInstance().getApplication().setDefaultLocale(currentLocale);
        } catch (Exception e) {
            logger.error(e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", e.getMessage()));
        }

        return null;
    }
}
